package com.example.my_dubbo.loadBalance;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author 何可人
 * @version 1.0
 * @description: TODO
 * @date 2022/12/9 10:38
 */
public class WeightRandomLoadBalance2 { // 权重总和为W。现在把这些权重值平铺在一维坐标值上
    public static void main(String[] args) {
        for(int i = 0;i<20;i++){
            System.out.println(getServerName());
        }
    }

    public static String getServerName(){

        int totalWeight = 0;
        boolean isAllsameWeight = true;
        //权重数组
        Object[] weights = ServerIps.WEIGHT_LIST.values().toArray();

        for(int i = 0;i<weights.length;i++){
            Integer weight = (Integer) weights[i];
            totalWeight+=weight; // 累计总和
            if(isAllsameWeight&&i>0&&!weight.equals(weights[i-1])){
                isAllsameWeight = false;
            }
        }

        if(!isAllsameWeight){
            Random random = new java.util.Random();
            int randomPos = random.nextInt(totalWeight);

            for(String ip:ServerIps.WEIGHT_LIST.keySet()){
                Integer ipweight = ServerIps.WEIGHT_LIST.get(ip);
                if(randomPos<ipweight){ // 在ipweight范围内
                    return ip;
                }else {
                    randomPos-=ipweight;
                }
            }
        }
        // 权重相同随机取一个或者上述条件不符合
        return (String) ServerIps.WEIGHT_LIST.keySet().toArray()[new Random().nextInt(ServerIps.WEIGHT_LIST.size())];
    }


}
